<?php
class Blog extends Model
{
    private $db;
    private $displayMarked = true;

    public function __construct()
    {
        $this->db = loadLib('DbMysql');    
        $s = loadModel('Setting');
        if ($s->getConfig('displayMarked') == 'false')
            $this->displayMarked = false;
    }

    public function find($id)
    {
        return $this->db->fetchRow('blog', 'id=' . $id);
    }

    public function totalItems()
    {
        return $this->db->count('blog', '1');
    }

    public function getBlogs($offset = 0, $count = 20)
    {
        $sql = "SELECT * FROM blog ORDER BY id DESC LIMIT {$offset}, {$count}";
        if (!$this->displayMarked)
            $sql = "SELECT * FROM blog WHERE marked=0 ORDER BY id DESC LIMIT {$offset}, {$count}";
        if (is_int($count))
            return $this->db->fetchAll($sql);
        return array();
    }

    public function getBlogsByTagId($tagId, $offset = 0, $count = 9999)
    {
        $where = "INSTR(tags, '#{$tagId}#')>0";
        if (!$this->displayMarked)
            $where .= ' AND marked=0 ';
        $sql = "SELECT * FROM blog WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$count}";
        return $this->db->fetchAll($sql);
    }

    public function getBlogsByKeyword($keyword, $offset = 0, $count = 9999)
    {
        $where = "content LIKE '%$keyword%'";
        if (!$this->displayMarked)
            $where .= ' AND marked=0 ';
        $sql = "SELECT * FROM blog WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$count}";
        return $this->db->fetchAll($sql);
    }

    public function countBlogByKeyword($keyword)
    {
        return $this->db->fetchResult('blog', 'count(1)', "content LIKE '%$keyword%'");
    }

    //@param $tagIds array
    public function addBlog($content, $tagIds, $dateline = null)
    {
        global $ENV;
        // eg:  #1#2#4#
        $tags = empty($tagIds)? '' : '#' . implode('#', $tagIds) . '#';
        if (is_null($dateline))
            $dateline = (int)$ENV['time'];
        $this->db->insert('blog', array('content' => $content, 'dateline' => $dateline, 'tags' => $tags));
        return $this->db->lastInsertId();
    }

    public function delete($id)
    {
        return $this->db->query('DELETE FROM blog WHERE id=' . $id);
    }

    public function setMark($id, $marked = 1)
    {
        return $this->db->update('blog', array('marked' => (int)$marked), 'id=' . $id);
    }
}
?>
